package cn.jy.careuplusdoctor.http;

import java.io.IOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.os.AsyncTask;
import android.text.TextUtils;
import cn.jy.careuplusdoctor.utils.LogUtils;

/**
 * 鑷畾涔塇ttpClient
 * @author lxy
 * @date 2015-07-14
 * @version v2.0
 */
public class CareuHttpClient {
	private static String TAG = "CareuHttpUrl";

	private static final String CHARSET_UTF8 = HTTP.UTF_8;
	private static DefaultHttpClient mHttpClient;
	private static CareuHttpClient instance;
	public static CareuHttpClient getIntance()
	{
		if (instance == null) {
			instance = new CareuHttpClient();
		}
		return instance;
	}
	private CareuHttpClient() {
	}
	
	public interface ResponseHandler{
		void onSuccess(String response);
		void onFail(String response);
	}
	
	/**
	 * http 寮傛璇锋眰
	 * @param url
	 * @param resHandler
	 */
	public void postHttpByAsyncTask(String url,final ResponseHandler resHandler)
	{
		final String requestUrl = url;
		new AsyncTask<Void, Void, String>() {
			@Override
			protected String doInBackground(Void... params){
				
				HttpPost post = new HttpPost(requestUrl);
				
				DefaultHttpClient httpClient = getHttpClient();
				
				try {
					HttpResponse response = httpClient.execute(post);
					if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
						HttpEntity entity = response.getEntity();
						String json = EntityUtils.toString(entity,CHARSET_UTF8);
						return json;
					}
					else {
						return "";
					}
				}
				/* 寮傚父鍏堢┖鐫�锛屼互鍚庡啀璇︾粏鏁寸悊  */
				catch(UnknownHostException e){
					e.printStackTrace();
					return null;
				}
				catch(SocketException e){
					e.printStackTrace();
					return null;
				}
				catch (SocketTimeoutException e) {
					return null;
				}
				catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return null;
				} 
				catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return null;
				}
			}
			@Override
			protected void onPostExecute(String result) {
				onProcessResponse(result,resHandler);
			}
		}.execute();
	}
	
	private void onProcessResponse(String result,ResponseHandler resHandler)
	{
		if (TextUtils.isEmpty(result)) {
			resHandler.onFail("fail");
		}
		else {
			resHandler.onSuccess(result);
		}
	}
	/**
	 * @param url
	 * @param params
	 * @param resHandler
	 */
	public void postHttpByAsyncTask(String url,Map<String, String> params,final ResponseHandler resHandler)
	{
		final String requestUrl = toUrl(url, params);
		postHttpByAsyncTask(requestUrl,resHandler);
	}
	
	/**
	 * @param url
	 * @param params
	 * @param resHandler
	 */
	public void postHttpByAsyncTask(String url,List<NameValuePair> params,final ResponseHandler resHandler)
	{
		final String requestUrl = toUrl(url, params);
		postHttpByAsyncTask(requestUrl,resHandler);
	}
	
	/**
	 * @param url
	 * @param params
	 * @param resHandler
	 */
	public void postHttpByAsyncTask(String url,final ResponseHandler resHandler,NameValuePair... params)
	{
		final String requestUrl = toUrl(url, params);
		postHttpByAsyncTask(requestUrl,resHandler);
	}

	/**
	 * 鍒涘缓httpClient瀹炰緥
	 * 
	 * @return
	 * @throws Exception
	 */
	private static synchronized DefaultHttpClient getHttpClient() {
		if (null == mHttpClient) {
			HttpParams params = new BasicHttpParams();
			// 璁剧疆涓�浜涘熀鏈弬鏁�
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, CHARSET_UTF8);
			HttpProtocolParams.setUseExpectContinue(params, true);
			HttpProtocolParams
					.setUserAgent(
							params,
							"Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
									+ "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
			// 瓒呮椂璁剧疆
			/* 浠庤繛鎺ユ睜涓彇杩炴帴鐨勮秴鏃舵椂闂� */
			ConnManagerParams.setTimeout(params, 1000*5);
			/* 杩炴帴瓒呮椂 */
			int ConnectionTimeOut = 1000*15;
			HttpConnectionParams
					.setConnectionTimeout(params, ConnectionTimeOut);
			/* 璇锋眰瓒呮椂 */
			HttpConnectionParams.setSoTimeout(params, 10000);
			// 璁剧疆鎴戜滑鐨凥ttpClient鏀寔HTTP鍜孒TTPS涓ょ妯″紡
			SchemeRegistry schReg = new SchemeRegistry();
			schReg.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));
			schReg.register(new Scheme("https", SSLSocketFactory
					.getSocketFactory(), 443));

			// 浣跨敤绾跨▼瀹夊叏鐨勮繛鎺ョ鐞嗘潵鍒涘缓HttpClient
			ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
					params, schReg);

			mHttpClient = new DefaultHttpClient(conMgr, params);
			
		}
		//ServerAuth();
		return mHttpClient;
	}
	
	public String toUrl(String url,Map<String, String> params)
	{
		StringBuffer sb = new StringBuffer();
		sb.append(url);
		if (params !=null && !params.isEmpty()) {
			Set<String> keys = params.keySet();
			
			sb.append("?");
			boolean hasNext = false;
			for (String key : keys)
			{
				sb.append(hasNext?"&":"");
				String value = params.get(key);
				sb.append(String.format("%s=%s", key,value));
				hasNext = true;
			}
		}
		LogUtils.i(TAG, sb.toString());
		return sb.toString();
	}
	
	/*private String replaceALL(String string) {
		String url=null;
		if(string!=null&&string!=""){
			url = string;
			url = url.replaceAll(" ", "%20");
			url = url.replaceAll("=", "%3D");
			url = url.replaceAll("|", "%124");
			url = url.replaceAll("+", "%2B");
			url = url.replaceAll("%", "%25");
			url = url.replaceAll("=", "%3D");
			url = url.replaceAll("#", "%23");
			url = url.replaceAll("/", "%2F");
		}
		return url;
		
	}*/
	public String toUrl(String url,List<NameValuePair> params)
	{
		StringBuffer sb = new StringBuffer();
		sb.append(url);
	
		if (params !=null && !params.isEmpty()) {
			sb.append("?");
			boolean hasNext = false;
			for (NameValuePair nameValuePair : params) {
				sb.append(hasNext?"&":"");
				sb.append(String.format("%s=%s", nameValuePair.getName(),nameValuePair.getValue()));
				hasNext = true;
			}
		}
		
		LogUtils.i(TAG, sb.toString());
		
		return sb.toString();
		
	}
	
	public String toUrl(String url,NameValuePair... nameValuePairs)
	{
		StringBuffer sb = new StringBuffer();
		sb.append(url);
	
		if (nameValuePairs != null) {
			sb.append("?");
			boolean hasNext = false;
			for (int i = 0; i < nameValuePairs.length; i++) {
				sb.append(hasNext?"&":"");
				sb.append(String.format("%s=%s", nameValuePairs[i].getName(),nameValuePairs[i].getValue()));
				hasNext = true;
			}
		}
		LogUtils.i(TAG, sb.toString());
		return sb.toString();
	}
	
	public List<NameValuePair> toNameValuePairList(NameValuePair... nameValuePairs)
	{
		if (nameValuePairs != null) {
			List<NameValuePair> list = new ArrayList<NameValuePair>();
			for (int i = 0; i < nameValuePairs.length; i++) {
				list.add(nameValuePairs[i]);
			}
			return list;
		}
		return null;
		
	}
	
	
}
